package com.jt.Advisor;

import com.jt.annotation.CacheFind;
import com.jt.util.OjbectMapperUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.ShardedJedis;

import java.lang.reflect.Method;
import java.util.Arrays;

/**
 * <p>
 *
 * </p>
 *
 * @author Song
 * @since 2020/11/12
 */
@Aspect
@Component
public class CacheAdvisor {

    @Autowired
    private JedisCluster jedis;

    @Around("@annotation(cacheFind)")
    public Object around(ProceedingJoinPoint pj,CacheFind cacheFind) throws Throwable {
        Object result = null;
        Object[] args = pj.getArgs();
        Class<?> aClass = pj.getTarget().getClass();
        MethodSignature methodSignature = (MethodSignature) pj.getSignature();
        Method declaredMethod = aClass.getDeclaredMethod(methodSignature.getName(), methodSignature.getParameterTypes());
       // CacheFind cacheFind = declaredMethod.getAnnotation(CacheFind.class);
        String value = "";
        int seconds = 0;
        if (cacheFind != null) {
            value = cacheFind.value();
            seconds = cacheFind.seconds();
        }
        String key = value + "::" + Arrays.toString(args);
        if (jedis.exists(key)) {
            result = OjbectMapperUtil.toOjbect(jedis.get(key), declaredMethod.getReturnType());
        } else {
            result = pj.proceed();
            if (seconds > 0) {
                jedis.setex(key, seconds, OjbectMapperUtil.toJson(result));
            } else {
                jedis.set(key, OjbectMapperUtil.toJson(result));
            }
        }
        return result;
    }
}
